<?php

namespace App\Http\Controllers;

use App\Models\Org;
use Hashids\Hashids;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class Controller extends BaseController
{
  use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

  private $_data;

  public function __construct()
  {
    $this->_data['error_code'] = 0;
    $this->_data['data'] = (object)[];
    $this->_data['error_message'] = '';
  }

  public function returnJSON($data, $status = 0, $msg = '', $StatusCode = 200, $patches = null)
  {
      $ret = [
          'status' => $status,
          'msg' => $msg,
          'data' => $data,
      ];

      if (!empty($patches)) {
          $ret['patches'] = $patches;
      }

      return new JsonResponse($ret, $StatusCode);
  }

  public function validate(Request $request, array $rules, array $messages = array(), callable $after = null)
  {
    $defaultMessages = [
      'required' => ':attribute字段不全',
      'max' => ':attribute字段长度不能超过:max'
    ];
    $validator = $this->getValidationFactory()->make($request->all(), $rules, array_merge($defaultMessages, $messages));
    if (!is_null($after)) {
      $validator->after($after);
    }
    if ($validator->fails()) {
      $this->throwValidationException($request, $validator);
    }
  }

  protected function buildFailedValidationResponse(Request $request, array $errors)
  {
    if ($request->ajax()) {
      return new JsonResponse([
        'status' => 422,
        'msg' => '验证错误',
        'errors' => $errors,
      ], 200);
    }
    return redirect()->to($this->getRedirectUrl())
      ->withInput($request->input())
      ->withErrors($errors, $this->errorBag());
  }

  // 默认首页全部转给前端
  public function defaultIndex(Request $request)
  {

      $vars = [
          'time' => time()
      ];
      //var_dump($request->wantsJson());exit;
      if (!preg_match('#^(login|logout|register|agreement|getpwd)(?:/|$)#', $request->path()) && !$request->user() && !$request->wantsJson()) {
      // if (!in_array($request->path(), ['login', 'logout', 'register', 'agreement']) && !$request->user() && !$request->wantsJson()) {
          return redirect('/login');
      } else if (preg_match('#^(login)(?:/|$)#', $request->path()) && $request->user()) {

       
          return redirect('/home');
      } else if (preg_match('#^(?:login|getpwd|register)/([^/]+$)#', $request->path(), $matches)) {
       
          $hasIds = new Hashids('', 10);
          $org_id = $hasIds->decode($matches[1]);
          if (empty($org_id)) {
              throw new \Exception('非法操作');
          } else if (is_array($org_id)) {
              $org_id = $org_id[0];
          }
          $org = Org::findOrFail($org_id);
          $vars['orgName'] = $org->name;
      }
      
      return view('admin.index')->with('vars', json_encode($vars));
  }

    // 默认首页全部转给前端
    public function upgrade()
    {
        return view('admin.upgrade');
    }

  public function response()
  {
    return response()->json($this->_data);
  }

  public function setStatus($status)
  {
    $this->_data['error_code'] = $status;
  }

  public function setMsg($errorMessage)
  {
    $this->_data['error_message'] = $errorMessage;
  }


  public function setData($data)
  {

    return is_array($data) ? $this->_data['data'] = $data : false;
  }

    public function setObject($data)
    {

        return is_object($data) ? $this->_data['data'] = $data : false;
    }

  public function getToken()
  {
    return request()->header('X-auth-token', '');
  }

  protected function rmNullProps(&$data) {
      foreach ($data as $key => $value) {
          if (is_null($value)) {
              unset($data[$key]);
          }
      }

      return $data;
  }
}
